<?php

namespace app\api\model;
use app\api\model\OauthOrder;
use app\common\enums\StatusEnum;
use app\common\controller\Send;

class Applepay extends \app\common\model\Applepay
{
    
    use send;
    /**
     * 用户登录授权
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function notify($data)
    {
        /*苹果内购的验证收据
         这里坑有点大.我这里是因为客户端传过来的验证收据已经进行base64加密了，所以后端无需再次加密，但是传到后端后+号会变成空格等导致老是出现21002错误，解决办法就是下面这样进行一次正则替换，如果客户端传过来的没有进行加密，则后端再进行一次base64加密即可。*/
        $receipt_data = $data['apple_receipt'];
        $orderid = $data['out_trade_no'];
        $attach  = $data['attach'];
        //获取订单信息
        $orderinfo = Applepay::getOne($orderid);
        if (!empty($orderinfo)) {
            // 验证支付状态
            $result = self::validate_apple_pay($receipt_data,$orderinfo,$attach);
            if($result['code']==0){
                // 验证通过后订单处理等逻辑
                return self::sendResult(self::$okCode, [],'购买成功');
            }else{
                // 验证不通过
                return self::sendResult(141, [],$result['message']);
            }
        }else{
            return self::sendResult(141, [],$result['message']);
        }
    }
    
    
    public static function curlHtml($url, $data = ''){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($data)) {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }
    
    
    public static function acurl($receipt_data, $sandbox=0) {
        //小票信息
        $POSTFIELDS = array("receipt-data" => $receipt_data);
        $POSTFIELDS = json_encode($POSTFIELDS);
    
        //正式购买地址 沙盒购买地址
        $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
        $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
        $url = $sandbox ? $url_sandbox : $url_buy;
        return self::curlHtml($url, $POSTFIELDS);
    }
    
    
    /**
     * 验证AppStore内付
     * @param  string $receipt_data 付款后凭证
     * @return array                验证是否成功
     */
    public static function validate_apple_pay($receipt_data,$orderinfo,$attach) {
        // 验证参数
        if (strlen($receipt_data)<20){
            $result = ['status'=>false, 'message'=>'非法参数'];
            return $result;
        }
        // 请求验证
        $html = self::acurl($receipt_data,1);
        $data = json_decode($html,true);
        // 如果是沙盒数据 则验证沙盒模式
        if($data['status'] == '21007'){
            // 请求验证
            $html = self::acurl($receipt_data, 1);
            $data = json_decode($html,true);
            $data['sandbox'] = '1';
        }
    
        if (isset($_GET['debug'])) {
            exit(json_encode($data));
        }
    
        // 判断是否购买成功
        if(intval($data['status']) === 0){
            // 支付回调处理
            $orderSn = $orderinfo['order_sn'];
            $totalFee= $orderinfo['money'];
            $data['transaction_id'] = $data['receipt']['in_app'][0]['transaction_id'];
            $payResult = OauthOrder::orderNotify($orderSn,$attach,$data['transaction_id'],$totalFee);
            return self::sendResult(self::$okCode, [], '购买成功');
        }else{
            return self::sendResult(102, [], '购买失败 status:'.$data['status']);
        }
    }
}